"""
多股票图表示例
展示如何使用多窗口管理器同时显示多只股票的K线图
"""

import sys
import os
from multi_window_manager import MultiWindowManager, run_multi_stock_charts


def example_tabbed_view():
    """示例1：标签页视图（推荐）"""
    print("示例1：标签页视图 - 在一个窗口中显示多只股票")
    
    # 股票信息列表
    stocks_info = [
        {"name": "沙隆达A (000554)", "path": "F:\\股票数据\\daily20250829\\daily\\000554.SZ.csv"},
        {"name": "平安银行 (000001)", "path": "F:\\股票数据\\daily20250829\\daily\\000001.SZ.csv"},
        {"name": "万科A (000002)", "path": "F:\\股票数据\\daily20250829\\daily\\000002.SZ.csv"},
        {"name": "国农科技 (000004)", "path": "F:\\股票数据\\daily20250829\\daily\\000004.SZ.csv"}
    ]
    
    # 检查文件是否存在
    valid_stocks = []
    for stock in stocks_info:
        if os.path.exists(stock["path"]):
            valid_stocks.append(stock)
            print(f"✓ 找到文件: {stock['name']}")
        else:
            print(f"✗ 文件不存在: {stock['name']} - {stock['path']}")
    
    if valid_stocks:
        try:
            run_multi_stock_charts(valid_stocks)
        except Exception as e:
            print(f"运行多股票图表时出错: {e}")
            import traceback
            traceback.print_exc()
    else:
        print("没有找到有效的股票数据文件")


def example_custom_manager():
    """示例2：自定义管理器"""
    print("示例2：自定义多窗口管理器")
    
    # 创建管理器
    manager = MultiWindowManager()
    
    try:
        # 股票信息
        stocks_info = [
            {"name": "测试股票1", "path": "F:\\股票数据\\daily20250829\\daily\\000554.SZ.csv"},
            {"name": "测试股票2", "path": "F:\\股票数据\\daily20250829\\daily\\000001.SZ.csv"}
        ]
        
        # 创建多股票窗口
        window = manager.create_multi_stock_window(stocks_info)
        window.setWindowTitle("自定义多股票窗口")
        window.resize(1400, 900)
        window.show()
        
        print("多股票窗口已创建，可以切换标签页查看不同股票")
        
        # 运行应用程序
        manager.run()
        
    except Exception as e:
        print(f"运行自定义管理器时出错: {e}")
        import traceback
        traceback.print_exc()
    finally:
        manager.cleanup()


def example_dynamic_loading():
    """示例3：动态加载股票"""
    print("示例3：动态加载股票数据")
    
    from PyQt5.QtWidgets import QApplication, QMainWindow, QVBoxLayout, QWidget, QPushButton, QLabel
    from PyQt5.QtCore import QThread, pyqtSignal
    
    class StockLoaderThread(QThread):
        """股票数据加载线程"""
        stock_loaded = pyqtSignal(str, str)  # 股票名, 文件路径
        finished = pyqtSignal()
        
        def __init__(self, stocks_info):
            super().__init__()
            self.stocks_info = stocks_info
        
        def run(self):
            for stock in self.stocks_info:
                if os.path.exists(stock["path"]):
                    self.stock_loaded.emit(stock["name"], stock["path"])
                    self.msleep(1000)  # 模拟加载时间
            self.finished.emit()
    
    class DynamicStockWindow(QMainWindow):
        def __init__(self):
            super().__init__()
            self.setWindowTitle("动态加载股票数据")
            self.setGeometry(100, 100, 800, 600)
            
            # 创建中央控件
            central_widget = QWidget()
            self.setCentralWidget(central_widget)
            
            layout = QVBoxLayout()
            central_widget.setLayout(layout)
            
            # 添加说明标签
            label = QLabel("点击按钮开始动态加载股票数据")
            layout.addWidget(label)
            
            # 添加加载按钮
            self.load_button = QPushButton("开始加载股票数据")
            self.load_button.clicked.connect(self.start_loading)
            layout.addWidget(self.load_button)
            
            # 添加状态标签
            self.status_label = QLabel("准备就绪")
            layout.addWidget(self.status_label)
            
            # 股票信息
            self.stocks_info = [
                {"name": "沙隆达A", "path": "F:\\股票数据\\daily20250829\\daily\\000554.SZ.csv"},
                {"name": "平安银行", "path": "F:\\股票数据\\daily20250829\\daily\\000001.SZ.csv"},
                {"name": "万科A", "path": "F:\\股票数据\\daily20250829\\daily\\000002.SZ.csv"}
            ]
            
            self.loaded_stocks = []
        
        def start_loading(self):
            """开始加载股票数据"""
            self.load_button.setEnabled(False)
            self.status_label.setText("正在加载股票数据...")
            
            # 创建加载线程
            self.loader_thread = StockLoaderThread(self.stocks_info)
            self.loader_thread.stock_loaded.connect(self.on_stock_loaded)
            self.loader_thread.finished.connect(self.on_loading_finished)
            self.loader_thread.start()
        
        def on_stock_loaded(self, name, path):
            """股票加载完成"""
            self.loaded_stocks.append({"name": name, "path": path})
            self.status_label.setText(f"已加载: {name}")
            print(f"已加载: {name}")
        
        def on_loading_finished(self):
            """加载完成"""
            self.load_button.setEnabled(True)
            self.status_label.setText(f"加载完成，共 {len(self.loaded_stocks)} 只股票")
            
            if self.loaded_stocks:
                # 创建多股票窗口
                try:
                    from multi_window_manager import MultiWindowManager
                    manager = MultiWindowManager()
                    window = manager.create_multi_stock_window(self.loaded_stocks)
                    window.show()
                    print("多股票窗口已创建")
                except Exception as e:
                    print(f"创建多股票窗口时出错: {e}")
    
    # 运行动态加载示例
    app = QApplication(sys.argv)
    window = DynamicStockWindow()
    window.show()
    sys.exit(app.exec_())


def main():
    """主函数"""
    print("多股票图表示例")
    print("=" * 50)
    
    examples = {
        "1": ("标签页视图（推荐）", example_tabbed_view),
        "2": ("自定义管理器", example_custom_manager),
        "3": ("动态加载股票", example_dynamic_loading)
    }
    
    print("请选择要运行的示例:")
    for key, (name, _) in examples.items():
        print(f"{key}. {name}")
    
    choice = input("请输入选择 (1-3): ").strip()
    
    if choice in examples:
        try:
            examples[choice][1]()
        except KeyboardInterrupt:
            print("\n程序被用户中断")
        except Exception as e:
            print(f"运行示例时出错: {e}")
            import traceback
            traceback.print_exc()
    else:
        print("无效选择")


if __name__ == "__main__":
    main()
